package com.company.cloud.page.modules.app.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.modules.api.response.Artist;
import com.company.cloud.art.modules.api.service.ArtArtistRemoteService;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchListParam;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchParam;
import com.company.cloud.behavior.modules.api.response.ThumbsUpSearchModel;
import com.company.cloud.behavior.modules.api.service.BehaviorClientService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BasePageParam;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.company.modules.api.request.ThirdPlatformValidateContentRequest;
import com.company.cloud.company.modules.api.response.CompanyFull;
import com.company.cloud.company.modules.api.response.ValidateContentResp;
import com.company.cloud.company.modules.api.service.CompanyConfigRemoteService;
import com.company.cloud.company.modules.api.service.CompanyRemoteService;
import com.company.cloud.page.modules.api.models.WechatMomentsModel;
import com.company.cloud.page.modules.api.service.PageClientService;
import com.company.cloud.page.modules.app.controller.req.SaveWechatMomentsParam;
import com.company.cloud.page.modules.app.controller.req.WechatMomentsQuery4PageParam;
import com.company.cloud.page.modules.base.entity.WechatMomentsInfo;
import com.company.cloud.page.modules.base.service.WechatMomentsInfoService;
import com.company.cloud.page.modules.cache.utils.MomentsConvertUtils;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.common.server.constant.IRelBusiType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;

@RestController
@RequestMapping("/app/cms/moments")
@Api(tags = "Page_App_我的动态管理")
public class WechatMomentsController {

	@Autowired
	private WechatMomentsInfoService wechatMomentsInfoService;

	@Qualifier("pageClientServiceImpl")
	@Autowired
	private PageClientService pageClientService;

	@Autowired
	private UserRemoteService userRemoteService;

	@Autowired
	private CompanyRemoteService companyRemoteService;

	@Autowired
	private ArtArtistRemoteService artArtistRemoteService;

	@Autowired
	private BehaviorClientService behaviorClientService;

	@Autowired
	private CompanyConfigRemoteService companyConfigRemoteService;



	@Login
	@PostMapping("/saveMoments")
	@ApiOperation(value = "保存动态", response = BaseResult.class)
	public BaseResult saveMoments(@RequestBody SaveWechatMomentsParam params) {
		ValidatorUtils.validate(params);

		if(StrUtil.isNotEmpty(params.getTitle())){
			BaseClientResult<ValidateContentResp>  result = companyConfigRemoteService.validateContent(new ThirdPlatformValidateContentRequest(params.getTitle()));
			ValidateContentResp vcr = BaseClientResult.getResultData(result);
			if(vcr==null || vcr.getCode()!=0){
				throw new BusinessException(BaseReturnEnum.PARAM_ERROR.getCode(),"非法内容");
			}
		}

		if(StrUtil.isNotEmpty(params.getContent())){
			BaseClientResult<ValidateContentResp>  result = companyConfigRemoteService.validateContent(new ThirdPlatformValidateContentRequest(params.getContent()));
			ValidateContentResp vcr = BaseClientResult.getResultData(result);
			if(vcr==null || vcr.getCode()!=0){
				throw new BusinessException(BaseReturnEnum.PARAM_ERROR.getCode(),"非法内容");
			}
		}

		if(params.getOrders()==null){
			params.setOrders(1);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();

		BaseClientResult<UserSimple> userSimpleResult = userRemoteService.getUserById(userInfo.getId());
		UserSimple userSimple= BaseClientResult.getResultData(userSimpleResult);

		WechatMomentsInfo entity =new WechatMomentsInfo();
		entity.setCompanyNo(userInfo.getCompanyNo());
		entity.setUserId(userInfo.getId());
		if(userSimple!=null && StrUtil.isNotEmpty(userSimple.getCustType()) && StrUtil.isNotEmpty(userSimple.getCustCode())){
			entity.setCustCode(userSimple.getCustCode());
			entity.setCustType(userSimple.getCustType());
		}else{
			entity.setCustType(IRelBusiType.UC_User_ID);
			entity.setCustCode(Convert.toStr(userInfo.getId()));
		}
		entity.setTitle(params.getTitle());
		entity.setContent(params.getContent());
		entity.setImgs(StrSplitUtils.list2string(params.getImgs()));
		entity.setVideos(StrSplitUtils.list2string(params.getVideos()));
		entity.setOrders(params.getOrders());
		entity.setRelIdType(params.getRelIdType());
		entity.setRelId(params.getRelId());
		entity.setState(BaseConstant.YNEnum.NO.getCode());
		entity.addCreateParam(userInfo);
		entity.addEditParam(userInfo);
		wechatMomentsInfoService.save(entity);
		return BaseResult.ok();
	}

	@Login
	@GetMapping("/delMoments")
	@ApiOperation(value = "删除动态", response = BaseResult.class)
	public BaseResult delMoments(@RequestParam("id") Integer id) {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();
		WechatMomentsInfo entity = wechatMomentsInfoService.getById(id);
		if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())
		|| !entity.getUserId().equals(userInfo.getId())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		wechatMomentsInfoService.updateById(entity);
		return BaseResult.ok();
	}


	@Login
	@PostMapping("/getMoments")
	@ApiOperation(value = "获取我的动态", response = WechatMomentsModel.class)
	public BaseResult getMoments(@RequestBody BasePageParam params) {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();
		IPage<WechatMomentsInfo> page = wechatMomentsInfoService.page(new Page<WechatMomentsInfo>(params.getPage(), params.getRows()),
				new QueryWrapper<WechatMomentsInfo>()
						.eq("user_id", userInfo.getId())
						.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
						.eq("state", BaseConstant.YNEnum.YES.getCode())
						.orderByDesc("orders","cdt")
		);



		Set<Integer> userIds=new HashSet<>();
		Set<String> companyNos=new HashSet<>();
		Set<String> artistNos=new HashSet<>();

		List<String> wechatMomentsIds=new ArrayList<>();

		page.getRecords().forEach(item->{
			wechatMomentsIds.add(item.getId().toString());
			if(StrUtil.isNotEmpty(item.getCustType()) && StrUtil.isNotEmpty(item.getCustCode())){
				if(IRelBusiType.UC_User_ID.equals(item.getCustType())){
					userIds.add(Convert.toInt(item.getCustCode()));
				}else if(IRelBusiType.UC_Company_ID.equals(item.getCustType())){
					companyNos.add(item.getCustCode());
				}else if(IRelBusiType.PTY_Artist_ObjType.equals(item.getCustType())){
					artistNos.add(item.getCustCode());
				}
			}
		});

		BaseClientResult<Map<Integer, UserSimple>>  userResult= userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap = BaseClientResult.getResultData(userResult,new HashMap<>());

		BaseClientResult<Map<String, CompanyFull>> companyResult= companyRemoteService.getCompanyMapFull(companyNos);
		Map<String, CompanyFull> companyMap=BaseClientResult.getResultData(companyResult,new HashMap<>());

		BaseClientResult<Map<String, Artist>> artistResult= artArtistRemoteService.artistInfoMap(artistNos);
		Map<String, Artist> artistMap=BaseClientResult.getResultData(artistResult,new HashMap<>());


		BehaviorSearchListParam bslp=new BehaviorSearchListParam();
		bslp.setObjType(IRelBusiType.CMS_Moment);
		bslp.setObjNo(wechatMomentsIds);
		BaseClientResult<Map<String, ThumbsUpSearchModel>> tusmResult=behaviorClientService.thumbsUpMap(bslp);
		Map<String, ThumbsUpSearchModel> tusmMap=BaseClientResult.getResultData(tusmResult,new HashMap<>());




		IPage<WechatMomentsModel> data=page.convert(new Function<WechatMomentsInfo, WechatMomentsModel>() {
			@Override
			public WechatMomentsModel apply(WechatMomentsInfo entity) {
				return MomentsConvertUtils.getWechatMomentsModel(entity,userMap,companyMap,artistMap,tusmMap);
			}
		});
		return BaseResult.ok(data);
	}


	@PostMapping("/query")
	@ApiOperation(value = "查询动态", response = WechatMomentsModel.class)
	public BaseResult query(@RequestBody WechatMomentsQuery4PageParam params) {
		String followUserSql=null;
		if(CheckUtils.hasInt(params.getFollowUserId())){
			followUserSql=StrUtil.format(
					"SELECT obj_no FROM base_user_follow_info where user_id={} and rows_state={} and obj_is_updown={} and obj_type in ('{}','{}','{}') ",
					params.getFollowUserId(),
					BaseConstant.EnabledEnum.ENABLED.getCode(),
					BaseConstant.YNEnum.YES.getCode(),
					IRelBusiType.UC_Company_ID,
					IRelBusiType.PTY_Artist_ObjType,
					IRelBusiType.UC_User_ID
					);
		}

		String video=null;
		String image=null;
		if(StrUtil.isNotEmpty(params.getFileType()) && "video".equals(params.getFileType())){
			video="video";
		}
		if(StrUtil.isNotEmpty(params.getFileType()) && "image".equals(params.getFileType())){
			image="image";
		}


		IPage<WechatMomentsInfo> page = wechatMomentsInfoService.page(new Page<WechatMomentsInfo>(params.getPage(), params.getRows()),
				new QueryWrapper<WechatMomentsInfo>()
						.eq(CheckUtils.hasInt(params.getUserId()),"user_id",params.getUserId())
						.eq(StrUtil.isNotEmpty(params.getCustType()),"cust_type",params.getCustType())
						.eq(StrUtil.isNotEmpty(params.getCustCode()),"cust_code",params.getCustCode())
						.eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
						.eq("state", BaseConstant.YNEnum.YES.getCode())
						.isNotNull(StrUtil.isNotEmpty(video),"videos")
						.isNotNull(StrUtil.isNotEmpty(image),"imgs")
						.inSql(StrUtil.isNotEmpty(followUserSql),"cust_code",followUserSql)

						.orderByDesc("orders","cdt")
		);

		if(page==null || CollUtil.isEmpty(page.getRecords())){
			return BaseResult.ok();
		}


		Set<Integer> userIds=new HashSet<>();
		Set<String> companyNos=new HashSet<>();
		Set<String> artistNos=new HashSet<>();

		List<String> wechatMomentsIds=new ArrayList<>();

		page.getRecords().forEach(item->{
			wechatMomentsIds.add(item.getId().toString());
			userIds.add(item.getUserId());
			if(StrUtil.isNotEmpty(item.getCustType()) && StrUtil.isNotEmpty(item.getCustCode())){
				if(IRelBusiType.UC_User_ID.equals(item.getCustType())){
					userIds.add(Convert.toInt(item.getCustCode()));
				}else if(IRelBusiType.UC_Company_ID.equals(item.getCustType())){
					companyNos.add(item.getCustCode());
				}else if(IRelBusiType.PTY_Artist_ObjType.equals(item.getCustType())){
					artistNos.add(item.getCustCode());
				}
			}
		});

		BaseClientResult<Map<Integer, UserSimple>>  userResult= userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap = BaseClientResult.getResultData(userResult,new HashMap<>());

		BaseClientResult<Map<String, CompanyFull>> companyResult= companyRemoteService.getCompanyMapFull(companyNos);
		Map<String, CompanyFull> companyMap=BaseClientResult.getResultData(companyResult,new HashMap<>());

		BaseClientResult<Map<String, Artist>> artistResult= artArtistRemoteService.artistInfoMap(artistNos);
		Map<String, Artist> artistMap=BaseClientResult.getResultData(artistResult,new HashMap<>());


		BehaviorSearchListParam bslp=new BehaviorSearchListParam();
		bslp.setObjType(IRelBusiType.CMS_Moment);
		bslp.setObjNo(wechatMomentsIds);
		BaseClientResult<Map<String, ThumbsUpSearchModel>> tusmResult=behaviorClientService.thumbsUpMap(bslp);
		Map<String, ThumbsUpSearchModel> tusmMap=BaseClientResult.getResultData(tusmResult,new HashMap<>());


		IPage<WechatMomentsModel> data=page.convert(new Function<WechatMomentsInfo, WechatMomentsModel>() {
			@Override
			public WechatMomentsModel apply(WechatMomentsInfo entity) {
				return MomentsConvertUtils.getWechatMomentsModel(entity,userMap,companyMap,artistMap,tusmMap);
			}
		});
		return BaseResult.ok(data);
	}


	@GetMapping("/get")
	@ApiOperation(value = "获取动态", response = WechatMomentsModel.class)
	public BaseResult get(@RequestParam("id") Integer id) {


		WechatMomentsInfo entity = wechatMomentsInfoService.getById(id);
		if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}

		Set<Integer> userIds=new HashSet<>();
		Set<String> companyNos=new HashSet<>();
		Set<String> artistNos=new HashSet<>();
		userIds.add(entity.getUserId());
		if(StrUtil.isNotEmpty(entity.getCustType()) && StrUtil.isNotEmpty(entity.getCustCode())){
			if(IRelBusiType.UC_User_ID.equals(entity.getCustType())){
				userIds.add(Convert.toInt(entity.getCustCode()));
			}else if(IRelBusiType.UC_Company_ID.equals(entity.getCustType())){
				companyNos.add(entity.getCustCode());
			}else if(IRelBusiType.PTY_Artist_ObjType.equals(entity.getCustType())){
				artistNos.add(entity.getCustCode());
			}
		}



		BaseClientResult<Map<Integer, UserSimple>>  userResult= userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap = BaseClientResult.getResultData(userResult,new HashMap<>());

		Map<String, CompanyFull> companyMap =new HashMap<>();
		if(companyNos.size()>0){
			BaseClientResult<Map<String, CompanyFull>> companyResult= companyRemoteService.getCompanyMapFull(companyNos);
			companyMap=BaseClientResult.getResultData(companyResult,new HashMap<>());
		}

		Map<String, Artist> artistMap=new HashMap<>();
		if(artistNos.size()>0){
			BaseClientResult<Map<String, Artist>> artistResult= artArtistRemoteService.artistInfoMap(artistNos);
			artistMap=BaseClientResult.getResultData(artistResult,new HashMap<>());
		}



		LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();

		BehaviorSearchParam bsp=new BehaviorSearchParam();
		if(userInfo!=null){
			bsp.setUserId(userInfo.getId());
		}
		bsp.setObjType(IRelBusiType.CMS_Moment);
		bsp.setObjNo(entity.getId().toString());
		bsp.setUserTop(10);
		BaseClientResult<ThumbsUpSearchModel>  tusmResult= behaviorClientService.getThumbsUpUserInfo(bsp);
		ThumbsUpSearchModel thumbsUpSearchModel = BaseClientResult.getResultData(tusmResult);
		WechatMomentsModel data= MomentsConvertUtils.getWechatMomentsModel(entity,userMap,companyMap,artistMap,null);
		data.setThumbsUp(thumbsUpSearchModel);
		return BaseResult.ok(data);
	}







}
